from selenium import  webdriver
from time import sleep
from selenium.webdriver.common.by import By



#多元素定位和处理
driver = webdriver.Chrome()
sleep(2)
driver.get("http://www.baidu.com")
sleep(2)
# elements = driver.find_elements(By.TAG_NAME,"input")
# print(type(elements))
# print(elements)
# for e in elements:
#     if e.get_attribute("id")=="kw":  #get_attribute 用来获取页面元素的某个属性值
#        e.send_keys("hello")
    # print(e.get_attribute("type"))
    # print(e.get_attribute("name"))
sleep(2)

# elements=driver.find_element(By.CSS_SELECTOR,"#kw")
# elements.send_keys(Keys.CONTROL,'a')
# 鼠标操作 ActionChains
from selenium.webdriver import ActionChains
#双击
# elements = driver.find_element(By.CSS_SELECTOR,"#kw")
# ActionChains(driver).send_keys_to_element(elements,"hello").click(elements).perform()
# sleep(2)
# ActionChains(driver).double_click(elements).perform() #双击
# sleep(2)
# ActionChains(driver).context_click(elements).perform()#右击
# sleep(2)
# element = driver.find_element(By.XPATH,'//*[@id="u"]/a[2]') #移动鼠标到指定元素
# ActionChains(driver).move_to_element(element).perform()
# sleep(2)
#键盘操作
# from selenium.webdriver import  Keys
# element = driver.find_element(By.CSS_SELECTOR,"#kw")
# element.send_keys(Keys.CONTROL,'a')
# sleep(2)
# element.send_keys(Keys.CONTROL,'c')
# sleep(2)
# element.send_keys(Keys.BACKSPACE)
# sleep(2)
# element.send_keys(Keys.CONTROL,'v')
# sleep(2)

#多个页面操作
# 句柄
handle1 = driver.current_window_handle
ele = driver.find_element(By.LINK_TEXT,"贴吧")
ele.click()
sleep(2)
ele = driver.find_element(By.LINK_TEXT,"文库")
ele.click()
sleep(2)
handles = driver.window_handles
for h in handles:
    if h != handle1:
        driver.switch_to.window(h)
        sleep(2)
        if driver.title == "百度新闻--海量中文资讯平台":
            driver.find_element(By.PARTIAL_LINK_TEXT,"连续第五年").click()
            sleep(5)
sleep(2)
driver.quit()